package mafia.younoodle.ilovemystuff;

import java.util.ArrayList;
import java.util.Collections;

import mafia.younoodle.ilovemystuff.data.Category;
import mafia.younoodle.ilovemystuff.data.RestClient;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;


public final class ConnectionTestActivity extends Activity {

	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.connection_test);
        
        StringBuilder responseString = new StringBuilder();
        
        // TODO get category list..
        final String url = "http://mystuff.ween.it/api/category/parent/0";
        final String urlItem = "http://mystuff.ween.it/api/item/category/";
        
        ArrayList<Category> categories = new ArrayList<Category>();

        RestClient client = new RestClient(url);
        try {
            client.Execute(RestClient.GET);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String responseCategory = client.getResponse();
        try {
			JSONArray jsonResult = new JSONArray(responseCategory);
			JSONObject jsonCategory;
			int parentId;
			for (int i=0, length=jsonResult.length(); i < length; i++) {
				jsonCategory = jsonResult.getJSONObject(i);
				if (jsonCategory.isNull("parent_category"))
					parentId = -1;
				else
					parentId = jsonCategory.getInt("parent_category");
				categories.add(new Category(jsonCategory.getInt("id"), jsonCategory.getString("name"), parentId));
			}
			Collections.sort(categories, Category.comparator);
			
		} catch (JSONException e) {
			e.printStackTrace();
			Log.e("STUFF", "json exception", e);
		}

		for (Category c : categories) {
			responseString.append(c.toString()).append("\n");
		}
		responseString.append("\n");
        
//        client = new RestClient(urlItem);
//        try {
//            client.Execute(RestClient.GET);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        responseString.append(client.getResponse());
		
		// TODO register product
		final String urlRegister = "http://mystuff.ween.it/api/user/";
		client = new RestClient(urlRegister);
		client.AddParam("item", "1");
		client.AddParam("uid", "1");
		try {
			client.Execute(RestClient.GET);
		} catch (Exception e) {
			e.printStackTrace();
  		}
		responseString.append(client.getResponse());
		
		

        TextView messageView = (TextView) findViewById(R.id.message_text);
        messageView.setText(responseString.toString());
    }
}
